﻿using AutoMapper;
using MediatR;
using SlaughterItem.Common.Domains.ListWeek2;
using SlaughterItem.Common.Dtos;
using SlaughterItem.Common.Infrastructures.Interfaces;
using SlaughterItem.Enum;

namespace SlaughterItem.API.Application.Commands.Week02.Killplan
{
    public class SlaughterCreateHandler : IRequestHandler<SlaughterCreateCommand, Result>
    {
        /// <summary>
        ///批宰计划
        /// </summary>
        private readonly IBaseRepository<Slaughter> slaughterRepository;
        private readonly IMapper mapper;
        private readonly IBaseRepository<LiveAnimals> liveAnimalsRepository;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="slaughterRepository"></param>
        /// <param name="mapper"></param>
        /// <param name="liveAnimalsRepository"></param>
        public SlaughterCreateHandler(IBaseRepository<Slaughter> slaughterRepository, IMapper mapper, IBaseRepository<LiveAnimals> liveAnimalsRepository)
        {
            this.slaughterRepository = slaughterRepository;
            this.mapper = mapper;
            this.liveAnimalsRepository = liveAnimalsRepository;
        }

        /// <summary>
        /// 业务逻辑
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(SlaughterCreateCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Added };
            try
            {
                //var res = liveAnimalsRepository.GetAll().FirstOrDefault(x => x.LiveAnimalsId == request.LiveAnimalsId);
                Slaughter slaughter = mapper.Map<Slaughter>(request);
                var res = slaughterRepository.Add(slaughter);
                if (res >0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Msg = "添加成功";
                }
            }
            catch (Exception)
            {

                throw;
            }
            return result;
        }
    }
}
